<?php

namespace Service\Http\Controller;

use Service\AjaxModel\AjaxResponse;
use Service\AjaxModel\PageableResponse;
use Service\Http\Exception\RestException;
use Service\Http\Request;
use Service\Model\Item;

class ItemController extends Controller
{
    /**
     * @throws RestException
     */
    public function get(Request $request): AjaxResponse
    {
        $item_id = $request->queryString['id'];
        $item = new Item();
        $item->selectById($item_id);
        return AjaxResponse::success($item);
    }

    /**
     * @throws RestException
     */
    public function create(Request $request): AjaxResponse
    {
        $user = $this->getUserObj($request);
        if (!$this->checkUserAdminRole($user)) {
            throw new RestException('用户无权访问', 403);
        }

        $item = new Item();
        $item->id = md5(rand());
        $item->title = $request->payload['title'];
        $item->subtitle = $request->payload['subtitle'];
        $item->money = $request->payload['money'];
        $item->img = $request->payload['money'];
        return AjaxResponse::success(['success' => $item->insert()]);
    }

    /**
     * @throws RestException
     */
    public function delete(Request $request): AjaxResponse
    {
        $user = $this->getUserObj($request);
        if (!$this->checkUserAdminRole($user)) {
            throw new RestException('用户无权访问', 403);
        }
        $item = new Item();
        $item->id = $request->payload['id'];
        return AjaxResponse::success(['success' => $item->delete()]);
    }

    public function search(Request $request)
    {
        $per_page = 10;
        $page = $request->queryString['page'];
        $offset = $page * $per_page;
        $keyword = $request->queryString['s'];
        $item = new Item();
        $max_num = $item->selectPageableCount([['title', 'LIKE', "%$keyword%"]]);
        $result = $item->selectPageable([['title', 'LIKE', "%$keyword%"]], $offset, $per_page);
        $result_array = $result->fetch_all(MYSQLI_ASSOC);
        return PageableResponse::success($result_array, $page, $max_num);
    }

    public function update(Request $request)
    {
        $user = $this->getUserObj($request);
        if (!$this->checkUserAdminRole($user)) {
            throw new RestException('用户无权访问', 403);
        }
// todo
//        return AjaxResponse::success(['success' => $item->delete()]);
    }

}
